package com.lanou3g.hw0512;

import com.sun.jndi.toolkit.dir.SearchFilter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Properties;

/**
 * Created by dllo on 18/5/14.
 */
@WebServlet(name = "CServlet",urlPatterns ="/search")
public class CServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端传输数据
        response.setContentType("text/html;charset=utf-8");
    String key =request.getParameter("key");
        try {
            Class.forName("com.mysql.jdbc.Driver");//加载驱动
            Properties properties = new Properties();
            //shiy9ong类名.class.getClassLoader()
            //获取 类加载器
            // 类加载器的getResourceAsStream
            //是相对于src路径下
            InputStream is = CServlet.class.getClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(is);
            String user = properties.getProperty("user");
            String password = properties.getProperty("password");

            Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/lanou_news",user,password);
            String sql="SELECT * from my_news where title like ?";
     PreparedStatement stataement = conn.prepareStatement(sql);
            stataement.setString(1,"%"+key+"%");
            ResultSet rs =stataement.executeQuery();
           PrintWriter pw = response.getWriter();
            while (rs.next()){
                int id=     rs.getInt("id");
                String title = rs.getString("title");
                pw.println(id+"-"+title);
                pw.println("<br/>");
            }
            rs.close();
            stataement.close();;
            conn.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
